package com.nsl.my_youlai.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nsl.my_youlai.common.enums.DocxTemplateStatusEnum;
import com.nsl.my_youlai.common.model.ElSelectOption;
import com.nsl.my_youlai.mapper.SysDeptMapper;
import com.nsl.my_youlai.model.entity.SysDept;
import com.nsl.my_youlai.service.SysDeptService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    /**
     * 部门下拉选项
     *
     * @return 部门下拉List集合
     */
    @Override
    public List<ElSelectOption> listDeptOptions() {

        List<SysDept> deptList = this.list(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getStatus, DocxTemplateStatusEnum.EDIT.getValue())
                .select(SysDept::getId, SysDept::getParentId, SysDept::getName)
                .orderByAsc(SysDept::getSort)
        );
        if (CollectionUtil.isEmpty(deptList)) {
            return Collections.EMPTY_LIST;
        }

        Set<Long> deptIds = deptList.stream()
                .map(SysDept::getId)
                .collect(Collectors.toSet());

        Set<Long> parentIds = deptList.stream()
                .map(SysDept::getParentId)
                .collect(Collectors.toSet());

        List<Long> rootIds = CollectionUtil.subtractToList(parentIds, deptIds);

        // 递归生成部门树形列表
        return rootIds.stream()
                .flatMap(rootId -> recurDeptTreeOptions(rootId, deptList).stream()).collect(Collectors.toList());

    }

    /**
     * 递归生成部门表格层级列表
     *
     * @param parentId 父ID
     * @param deptList 部门列表
     * @return 部门表格层级列表
     */
    public static List<ElSelectOption> recurDeptTreeOptions(long parentId, List<SysDept> deptList) {
        List<ElSelectOption> list = CollectionUtil.emptyIfNull(deptList).stream()
                .filter(dept -> dept.getParentId().equals(parentId))
                .map(dept -> {
                    ElSelectOption elSelectOption = new ElSelectOption(dept.getId(), dept.getName());
                    List<ElSelectOption> children = recurDeptTreeOptions(dept.getId(), deptList);
                    if (CollectionUtil.isNotEmpty(children)) {
                        elSelectOption.setChildren(children);
                    }
                    return elSelectOption;
                })
                .collect(Collectors.toList());
        return list;
    }
}
